package web.controller;

import framework.storage.FileStorage;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import system.utils.MimeUtil;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;

@Api(tags = "文件接口")
@RestController
@RequestMapping("/file/")
public class FileController {

    @Autowired
    private FileStorage fileStorage;

    // http://192.168.1.100/xsys/file/g/2022/01/01/1424123451.jpg
    // file path: -> /g/2022/01/01/1424123451.jpg
    @ApiOperation("公众文件(无需授权)")
    @GetMapping("/g/**")
    public void publicFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String servletPath = request.getServletPath();
        if (servletPath.startsWith("/file/g/")) {
            servletPath = servletPath.substring("/file/".length() - 1);
        }
        //
        String ext = FilenameUtils.getExtension(servletPath).toLowerCase();
        try (InputStream inputStream = this.fileStorage.getStream(servletPath)) {
            MimeUtil.setResponseMime(response, ext);
            MimeUtil.setDisposition(request,response);
            IOUtils.copy(inputStream, response.getOutputStream());
        }
    }

    // http://192.168.1.100/xsys/file/s/2022/01/01/1424123451.jpg
    // file path: -> /s/2022/01/01/1424123451.jpg
    @ApiOperation("私有文件(登录后可访问)")
    @GetMapping("/s/**")
    public void privateFile(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String servletPath = request.getServletPath();
        if (servletPath.startsWith("/file/s/")) {
            servletPath = servletPath.substring("/file/".length() - 1);
        }
        //
        String ext = FilenameUtils.getExtension(servletPath).toLowerCase();
        try (InputStream inputStream = this.fileStorage.getStream(servletPath)) {
            MimeUtil.setResponseMime(response, ext);
            MimeUtil.setDisposition(request,response);
            IOUtils.copy(inputStream, response.getOutputStream());
        }
    }

}
